package com.example.java_websocket.web.websocket;


import com.example.java_websocket.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;
import javax.websocket.Session;
import java.io.IOException;

@Component
@Slf4j
public class MessageBroadcaster {
    //CHANNEL 是 Redis 的频道名称，用于发布和订阅消息。
    //这里的频道名是 chat_channel，表示这是一个与聊天相关的频道
//    private static final String CHANNEL = "chat_channel";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 发送消息到频道
//    public void broadcast(String message) {
//
//        redisTemplate.convertAndSend(CHANNEL, message);
//    }

public void publishMessage(String message){
    // 向指定channel发送消息
    redisTemplate.convertAndSend(RedisConfig.CHANNEL,message);
}
       // 消息监听容器（需配置）
    // 接收消息,并且广播给本地所有session
    @Bean
    public MessageListenerAdapter listenerAdapter() {
//        return new MessageListenerAdapter(new MessageListener() {
//            @Override
//            public void onMessage(Message message, byte[] pattern) {
//                String msg = new String(message.getBody(), StandardCharsets.UTF_8);
//                // 实际处理逻辑...
//                System.out.println("订阅消息: " + msg);
//            }
//        });
        return new MessageListenerAdapter((MessageListener)(message, Pattern) -> {
            String msg = new String(message.getBody());
            log.info("收到消息：{}", msg);
            for (Session session : Chat1WebSocket.sessionMap.values()) {
                // 给所有的客户端推送ws消息
                try {
                    session.getBasicRemote().sendText(msg);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

}
